#!/usr/bin/env python
import sys		
		
class FoldSegment:

	def __init__( self, FoldTree ):
		self.StartLineIter  = None
		self.LineTabSpaces  = 0
		self.Collapsed      = False
		self.X              = -1
		self.Y              = -1
		self.Width          = 9
		self.Height         = 9
		self.FoldTree       = FoldTree
		#test
		
	def IsOnNode( self, mouse_x, mouse_y ):
		ret = False
		if mouse_x >= self.X and mouse_x <= self.X + self.Width :
			if mouse_y >= self.Y and mouse_y <= self.Y + self.Height:
				ret = True
		return ret	
	
	def GetLastIter( self ):
		ret            = None
		TextEditor     = self.FoldTree.FoldingMargin.TextEditor
		end_iter       = self.StartLineIter.copy()
		while end_iter.forward_line():
			end_line_iter =  end_iter.copy()
			end_line_iter.forward_to_line_end()
			line = TextEditor.TextBuffer.get_text( end_iter, end_line_iter )
			tabs = line.count("\t")
			#daca gasesc mai putine taburi decat la inceput, am gasit finalul
			if tabs < self.LineTabSpaces: break
		#daca am ultimul rand gol, fara nimic pe el, treci la linia de dinainte
		iter   = end_iter.copy()
		iter.backward_line()
		e_iter = iter.copy()
		e_iter.forward_to_line_end()
		line   = TextEditor.TextBuffer.get_text( iter, e_iter )
		if len( line.strip() ) == 0: end_iter.backward_line()
		#
		ret            = end_iter
		return ret
	
	def GetText( self ):
		TextEditor = self.FoldTree.FoldingMargin.TextEditor
		start_iter = self.StartLineIter.copy()
		end_iter   = self.GetLastIter()
		return TextEditor.TextBuffer.get_text( start_iter, end_iter )
	
	def CheckIfSliceIsFolded( self ):
		TextEditor     = self.FoldTree.FoldingMargin.TextEditor
		tag            = TextEditor.TextBuffer.get_tag_table().lookup("fold-title")
		return self.StartLineIter.begins_tag( tag )
	
		
	def Fold( self ):
		self.Collapsed = True
		TextEditor     = self.FoldTree.FoldingMargin.TextEditor
		#seteaza titlul de fold
		TextEditor.SetFoldTitle( self.StartLineIter )
		#hide text from next line
		start_next_line_iter = self.StartLineIter.copy()
		start_next_line_iter.forward_line()
		TextEditor.HideText( start_next_line_iter, self.GetLastIter() )
		#refresh margin
		TextEditor.RefreshMargin()
	
	def Unfold( self ):
		self.Collapsed = False
		TextEditor     = self.FoldTree.FoldingMargin.TextEditor
		#deseteaza titlul de fold
		TextEditor.RemoveFoldTitle( self.StartLineIter )
		#arata textul ascuns de dupa linia curenta
		start_next_line_iter = self.StartLineIter.copy()
		start_next_line_iter.forward_line()
		TextEditor.ShowHiddenText( start_next_line_iter, self.GetLastIter() )
		#refresh margin
		TextEditor.RefreshMargin()
		
	def ToString( self ):
		print "[segment start='" + str(self.StartLineIter.get_line()) + "' end='" + str(self.GetLastIter().get_line()) + "']"
